import React, { useState, useEffect } from 'react';
import { Card, Form, Input, Button, message, Checkbox } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';

import { apiClients, tokenManager } from '@/services/apiClient';
import type { TokenObtainPairRequest } from '@/services/generated';

// 记住我功能的本地存储键
const REMEMBER_EMAIL_KEY = 'remembered_email';
const REMEMBER_ME_KEY = 'remember_me';

const Login: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();

  // 组件加载时检查是否有记住的用户信息
  useEffect(() => {
    const rememberedEmail = localStorage.getItem(REMEMBER_EMAIL_KEY);
    const rememberMe = localStorage.getItem(REMEMBER_ME_KEY) === 'true';

    if (rememberedEmail && rememberMe) {
      form.setFieldsValue({
        email: rememberedEmail,
        remember: true
      });
    }
  }, [form]);

  const handleLogin = async (values: TokenObtainPairRequest & { remember?: boolean }) => {
    try {
      setLoading(true);

      // 处理"记住我"功能
      if (values.remember) {
        // 保存用户邮箱和记住我状态
        localStorage.setItem(REMEMBER_EMAIL_KEY, values.email);
        localStorage.setItem(REMEMBER_ME_KEY, 'true');
      } else {
        // 清除记住的信息
        localStorage.removeItem(REMEMBER_EMAIL_KEY);
        localStorage.removeItem(REMEMBER_ME_KEY);
      }

      // 从values中移除remember字段，因为后端不需要这个字段
      const { remember, ...loginData } = values;

      const response = await apiClients.auth.authTokenCreate({
        tokenObtainPairRequest: loginData
      });

      const tokenData = response.data;
      if (tokenData?.access) {
        tokenManager.setToken(tokenData.access);
        tokenManager.setRefreshToken(tokenData.refresh || '');

        // 如果选择了记住我，设置更长的Token过期时间标记
        if (remember) {
          localStorage.setItem('token_remember', 'true');
        } else {
          localStorage.removeItem('token_remember');
        }

        message.success('登录成功');
        history.push('/');
      }
    } catch (error: any) {
      // API中间件已经处理了错误显示，这里只需要记录日志
      console.error('登录失败:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{
      minHeight: '100vh',
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      padding: '20px',
      boxSizing: 'border-box'
    }}>
      <Card
        title="用户登录"
        style={{
          width: '100%',
          maxWidth: 400,
          boxShadow: '0 4px 12px rgba(0,0,0,0.15)'
        }}
      >
        <Form
          form={form}
          name="login"
          onFinish={handleLogin}
          autoComplete="off"
          size="large"
        >
          <Form.Item
            name="email"
            rules={[
              { required: true, message: '请输入邮箱!' },
              { type: 'email', message: '请输入有效的邮箱地址!' },
            ]}
          >
            <Input
              prefix={<MailOutlined />}
              placeholder="邮箱地址"
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              { required: true, message: '请输入密码!' },
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
            />
          </Form.Item>

          <Form.Item name="remember" valuePropName="checked">
            <Checkbox>记住我</Checkbox>
          </Form.Item>

          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              loading={loading}
              style={{ width: '100%' }}
            >
              登录
            </Button>
          </Form.Item>

          <div style={{ textAlign: 'center' }}>
            <a href="/user/register">还没有账号？立即注册</a>
          </div>
        </Form>
      </Card>
    </div>
  );
};

export default Login;
